import React, { useState, useEffect } from 'react'
import './index.modules.scss'
import { province } from '@/components/js/addressOptions'
import { baseURL } from '@/http/request'
import SearchView from '@/components/searchView/index'
import {
  Space,
  Table,
  Button,
  Modal,
  Card,
  message,
  Form,
  Input,
  Popconfirm,
  Pagination,
  Select,
  Upload
} from 'antd'
import { FolderOpenOutlined } from '@ant-design/icons'
import {
  filmList,
  filmListAdd,
  filmListChange,
  filmSerach,
  filmCreateExcel,
  filmListDelete
} from '@/http/api/carBrand'
import { getstorelistAll } from '@/http/api/store'
let pageData = {
  page: 1,
  size: 10,
  total: 0
}
let optionsFilmType = [
  { value: '漆面膜', label: '漆面膜' },
  { value: '改色膜', label: '改色膜' },
  { value: '车顶膜', label: '车顶膜' },
  { value: '太阳膜', label: '太阳膜' }
]

let typeList = [
  {
    title: '产品类型',
    type: 'inpute',
    model: 'type'
  },
  {
    title: '产品型号',
    type: 'inpute',
    model: 'name'
  },
  {
    title: '使用权限',
    type: 'inpute',
    model: 'authority'
  },
  {
    title: '可用门店',
    type: 'inpute',
    model: 'usableStoreName'
  }
]
let _id = ''
let selectedRowsdata = []
const App = React.forwardRef((props, ref) => {
  const [messageApi, contextHolder] = message.useMessage()
  const handleChildMethod = () => {
    getList()
    getStore()
  }

  React.useImperativeHandle(ref, () => ({
    handleChildMethod
  }))
  const [dataSource, setDataSource] = useState([])
  const [isShowAdd, serIsShowAdd] = useState(false)
  const [form] = Form.useForm()
  const [optionsStore, setOptionsStore] = useState([
    {
      value: 'all',
      label: '所有门店'
    }
  ])
  const columns = [
    {
      title: '产品类型',
      dataIndex: 'type',
      align: 'center'
    },
    {
      title: '产品型号',
      dataIndex: 'name',
      align: 'center'
    },
    {
      title: '产品编号',
      dataIndex: 'nameNumber',
      align: 'center'
    },
    {
      title: '质保年限',
      dataIndex: 'age',
      align: 'center'
    },
    {
      title: '使用次数',
      dataIndex: 'countAll',
      align: 'center'
    },
    {
      title: '使用权限',
      dataIndex: 'authority',
      align: 'center'
    },
    {
      title: '可用门店',
      dataIndex: 'usableStoreName',
      align: 'center',
      render: (usableStoreName) => {
        return (
          <div className="tableText">
            {JSON.parse(usableStoreName)?.join(',')}
          </div>
        )
      }
    },
    {
      title: '产品图片',
      dataIndex: 'image',
      align: 'center',
      render: (image) => {
        return (
          <div className="tableImageBox">
            {/* {image} */}
            <img className="tableImage" src={image} alt="" srcset="" />
          </div>
        )
      }
    },
    {
      title: 'A3车价格',
      dataIndex: 'A3Price',
      align: 'center'
    },
    {
      title: 'A5车价格',
      dataIndex: 'A5Price',
      align: 'center'
    },
    {
      title: 'A7车价格',
      dataIndex: 'A7Price',
      align: 'center'
    },
    {
      title: 'A8车价格',
      dataIndex: 'A8Price',
      align: 'center'
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (data) => (
        <Space size="middle">
          <Button
            type="primary"
            onClick={() => {
              changeClickFn(data)
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="删除"
            description="确定删除吗?"
            placement="top"
            onConfirm={() => {
              DeleteFn(data)
            }}
            onCancel={() => {
              message.error('取消删除')
            }}
            okText="是"
            cancelText="不"
          >
            <Button type="primary" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      selectedRowsdata = selectedRows.map((item) => {
        return item._id
      })
    }
  }
  // 获取列表
  const getList = async () => {
    pageData.appid = localStorage.getItem('appid')
    const res = await filmList(pageData)
    setDataSource(
      res.data.res.map((item) => {
        return {
          ...item,
          key: item._id
        }
      })
    )
    pageData.total = res.data.total
  }
  // 获取所有门店列表
  const getStore = async () => {
    const res = await getstorelistAll({
      appid: localStorage.getItem('appid'),
      status: 1
    })

    setOptionsStore([
      ...optionsStore,
      ...res.data.res.map((item) => {
        return {
          value: item._id,
          label: item.name
        }
      })
    ])
  }
  // 点击编辑
  const changeClickFn = (data) => {
    let addData = { ...data }
    addData.usableStore = JSON.parse(addData.usableStore)
    if (addData._id) {
      form.setFieldsValue(addData)
      _id = addData._id
    }
    serIsShowAdd(true)
  }
  // 添加
  const onFinish = async (data) => {
    console.log(data)
    let upData = JSON.parse(JSON.stringify(data))
    if (upData.image && !_id) {
      upData.image.fileList.forEach(async (item, index) => {
        let res = ''
        data.appid = localStorage.getItem('appid')
        data.usableStoreName = []
        data.usableStore.forEach((item) => {
          optionsStore.forEach((item2) => {
            if (item == item2.value) {
              data.usableStoreName.push(item2.label)
            }
          })
        })
        data.image = item.response.image_url
        res = await filmListAdd(data)
        if (res.data.type == 1) {
          messageApi.success(res.data.message)
        } else {
          messageApi.error(res.data.message)
        }
        getList()
        serIsShowAdd(false)
        form.resetFields()
        _id = ''
      })
    } else {
      let res = ''
      data.appid = localStorage.getItem('appid')
      data.usableStoreName = []
      data.usableStore.forEach((item) => {
        optionsStore.forEach((item2) => {
          if (item == item2.value) {
            data.usableStoreName.push(item2.label)
          }
        })
      })
      data.image = data.image
        ? data.image.fileList[0]?.response.image_url
        : data.image
      if (_id) {
        data._id = _id
        res = await filmListChange(data)
      } else {
        res = await filmListAdd(data)
      }
      if (res.data.type == 1) {
        messageApi.success(res.data.message)
      } else {
        messageApi.error(res.data.message)
      }
      getList()
      serIsShowAdd(false)
      form.resetFields()
      _id = ''
    }
  }
  const pageChangeFn = (page, pageSize) => {
    pageData.page = page
    pageData.size = pageSize
    getList()
  }
  const porpsData = async (data) => {
    pageData = {
      page: 1,
      size: 10,
      total: 0,
      appid: localStorage.getItem('appid'),
      ...data
    }
    const res = await filmSerach(pageData)
    setDataSource(
      res.data.res.map((item) => {
        return {
          ...item,
          key: item._id
        }
      })
    )
    pageData.total = res.data.total
  }
  // 门店选择事件
  const selectChangeFn = (data) => {
    console.log(data)
    data.forEach((item, index) => {
      if (item == 'all' && index != 0) {
        form.setFieldsValue({
          usableStore: ['all']
        })
      } else if (item == 'all' && index == 0) {
        form.setFieldsValue({
          usableStore: [data[index]]
        })
      }
    })
    console.log(form.getFieldValue().usableStore)
  }
  // 删除
  const DeleteFn = async (data) => {
    const res = await filmListDelete({ id: data._id })
    messageApi.success(res.data.message)
    getList()
  }
  // 导出
  const exportExcel = async () => {
    let data = {
      id: 'all',
      appid: localStorage.getItem('appid')
    }
    if (selectedRowsdata.length != 0) {
      data.id = selectedRowsdata
    }
    const res = await filmCreateExcel(data)
    const url = window.URL.createObjectURL(new Blob([res.data]))
    const a = document.createElement('a')
    a.href = url
    a.download = '膜信息.xlsx'
    document.body.appendChild(a)
    a.click()
    window.URL.revokeObjectURL(url)
  }
  return (
    <div>
      <Card>
        <SearchView typeList={typeList} porpsData={porpsData}></SearchView>
        <div className="headerButton">
          <Button
            style={{ marginRight: '10px' }}
            type="primary"
            onClick={() => {
              serIsShowAdd(true)
            }}
          >
            新增
          </Button>
          <Button
            type="primary"
            onClick={() => {
              exportExcel()
            }}
          >
            导出
          </Button>
        </div>
        <Table
          rowSelection={{
            type: 'checkbox',
            ...rowSelection
          }}
          pagination={false}
          bordered
          rowKey="key"
          columns={columns}
          dataSource={dataSource}
        />
        <div className="Pagin">
          <Pagination
            onChange={pageChangeFn}
            defaultCurrent={pageData.page}
            total={pageData.total}
          />
        </div>
      </Card>
      <div>
        <Modal
          title="添加"
          footer={[]}
          onCancel={() => {
            serIsShowAdd(false)
            form.resetFields()
            _id = ''
          }}
          open={isShowAdd}
        >
          <Form
            labelCol={{
              span: 5
            }}
            wrapperCol={{
              span: 14
            }}
            layout="horizontal"
            style={{
              maxWidth: 800
            }}
            form={form}
            onFinish={onFinish}
          >
            <Form.Item
              label="产品类型"
              name="type"
              rules={[
                {
                  required: true,
                  message: '请选择'
                }
              ]}
            >
              <Select className="inputeStyle" options={optionsFilmType} />
            </Form.Item>
            <Form.Item
              label="产品型号"
              name="name"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="产品编号"
              name="nameNumber"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item label="产品图片" name="image">
              <Upload
                accept=".jpg,.png"
                maxCount={1000}
                action={baseURL + 'api/uploadAvatar'}
                multiple={true}
              >
                <Input
                  placeholder="请选择图片"
                  suffix={<FolderOpenOutlined />}
                />
              </Upload>
            </Form.Item>
            <Form.Item
              label="质保年限"
              name="age"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="使用次数"
              name="countAll"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>

            <Form.Item
              label="漆面膜次数"
              name="lacquerNumber"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="改色膜次数"
              name="colorAlterationNumber"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="车顶膜次数"
              name="roofNumber"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="太阳膜次数"
              name="sunNumber"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>

            <Form.Item
              label="使用权限"
              name="authority"
              rules={[
                {
                  required: true,
                  message: '请选择'
                }
              ]}
            >
              <Select
                className="inputeStyle"
                options={[
                  { value: '公有', label: '公有' },
                  { value: '私有', label: '私有' }
                ]}
              />
            </Form.Item>
            <Form.Item
              label="省份"
              name="province"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Select className="inputeStyle" options={province} />
            </Form.Item>
            <Form.Item
              label="可用门店"
              name="usableStore"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Select
                mode="multiple"
                allowClear
                style={{
                  width: '100%'
                }}
                placeholder="请选择"
                options={optionsStore}
                onChange={selectChangeFn}
              />
            </Form.Item>
            <Form.Item
              label="A3"
              name="A3Price"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="A5"
              name="A5Price"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="A7"
              name="A7Price"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              label="A8"
              name="A8Price"
              rules={[
                {
                  required: true,
                  message: '请输入'
                }
              ]}
            >
              <Input className="inputeStyle" />
            </Form.Item>
            <Form.Item
              wrapperCol={{
                offset: 6,
                span: 16
              }}
            >
              <Button
                type="primary"
                onClick={() => {
                  form.resetFields()
                  serIsShowAdd(false)
                }}
              >
                取消
              </Button>
              <Button
                style={{ marginLeft: '10px' }}
                type="primary"
                htmlType="submit"
              >
                确定
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
      {contextHolder}
    </div>
  )
})
export default App
